//
//  FSNoticeViewController.m
//  WZSOA
//
//  Created by 刘沿 on 16/6/27.
//  Copyright © 2016年 刘沿. All rights reserved.
//

#import "FSNoticeViewController.h"
#import "GDataDefines.h"


@interface FSNoticeViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,assign)int totalCounts; //总条数
@property(nonatomic,assign)int currentPage; //当前页

@property (nonatomic,strong) UITableView *tableView;

@end

@implementation FSNoticeViewController

-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        
        _dataArray = [NSMutableArray array];
    }

    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor colorWithRed:188/255.0 green:193/255.0 blue:196/255.0 alpha:1];
    
    UITableView *tab = [[UITableView alloc] init];
    
//不设置这个会下移一段距离
    self.automaticallyAdjustsScrollViewInsets = NO;
    _tableView = tab;
    _tableView.delegate = self;
    _tableView.dataSource = self;

    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view.mas_top).mas_offset(64);
        
        make.left.equalTo(self.view.mas_left).mas_offset(20);
        
        make.right.equalTo(self.view.mas_right).mas_offset(-20);
        
        make.bottom.equalTo(self.view.mas_bottom).mas_offset(-20);
    }];
    
    __weak typeof (self) weakSelf = self;

    [self.tableView addHeaderWithCallback:^{
        weakSelf.currentPage = 1;
        [weakSelf loadData]; //加载网络数据
    }];
    [self.tableView headerBeginRefreshing];
    

    [self.tableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
            [weakSelf loadMore];
            
        }else{
            
            [weakSelf.tableView footerEndRefreshing];
            [weakSelf.view makeToast:@"没有更多了"];
            
        }
        
    }];

}


#pragma mark 加载网络数据
-(void)loadData{
    
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools postWithURL:KexchgeneralURL arrays:array method:KelectronicsPage success:^(id JSON) {
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
        self.dataArray =  [self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]];
        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
            [self.view makeToast:@"暂时还没数据哦"];
        }
    } failure:^(NSError *error) {
        [self.tableView headerEndRefreshing];
    }];
    
}

#pragma mark 加载更多
-(void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools postWithURL:KexchgeneralURL arrays:array method:KelectronicsPage success:^(id JSON) {
        [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        self.currentPage++;
        [self.tableView footerEndRefreshing];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView footerEndRefreshing];
    }];
    
}


//得到服务器返回数据中的标题
//传参数：一个服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            FSReceiveModel * model = [[FSReceiveModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"接收时间"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.fileId = [fileIdElement stringValue];
            [array addObject:model];
        }
    }
    
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue] ;
        
    }
    self.title = [NSString stringWithFormat:@"近期公告(%d)",self.totalCounts];
    return array;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    FSReceiveModel * model = self.dataArray[indexPath.row];
    CGFloat height = 0;
    CGFloat  titlesize  = [FSHightTool heightbyString:model.title font:14 minsWidth:80];
    
    NSString * desstring = [NSString stringWithFormat:@"%@",model.time];
    CGFloat dessize = [FSHightTool heightbyString:desstring font:13 minsWidth:40];;
    height = titlesize + dessize + 30;
    return  height;
}




#pragma mark UITableView dataScource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FSUpDoingReceiveCell * cell = [FSUpDoingReceiveCell UpDoingReceiveCell];
    FSReceiveModel * model = self.dataArray[indexPath.row];
    cell.receiveModel = model;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    FSReceiveModel * model = self.dataArray[indexPath.row];
    OANoteDetailViewController * noteVC = (OANoteDetailViewController*)[sb instantiateViewControllerWithIdentifier:@"NoteDetailVC"];
    noteVC.fileId = model.fileId;
    [self.navigationController pushViewController:noteVC animated:YES];
    
}


@end




















